package com.javaee.wordtree.controller;

import com.javaee.wordtree.common.*;
import com.javaee.wordtree.service.StatisticService;
import com.javaee.wordtree.service.LearningAnalysisService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/statistic")
public class StatisticController {

    @Resource
    StatisticService statisticService;

    @Resource
    LearningAnalysisService learningAnalysisService;

    @GetMapping("/{userID}/{belongBook}")
    public Result<?> getStatistics(@PathVariable String userID, @PathVariable String belongBook) {

        List<LineData> lineChartData = statisticService.findLatestSevenDaysTimeData(userID);
        List<ColumnData> columnChartData = statisticService.findLatestSevenDaysWordData(userID);
        List<CircleData> circleChartData = statisticService.findMmryPercentage(userID);
        int learnedWordCount = statisticService.getLearnedWordCount(userID);
        int totalWordCount = statisticService.getTotalWordCount(belongBook);
        int needReviewWordCount = statisticService.getNeedReviewWordCount(userID);

        StatisticData statisticData = new StatisticData(needReviewWordCount, learnedWordCount, totalWordCount,
                columnChartData, circleChartData, lineChartData);
        return Result.success(statisticData);

    }

    /**
     * 获取AI学习分析报告
     * 
     * @param userID     用户ID
     * @param belongBook 所属词书
     * @return AI分析报告
     */
    @PostMapping("/analysis/{userID}/{belongBook}")
    public Result<?> getLearningAnalysis(@PathVariable String userID, @PathVariable String belongBook) {
        try {
            String analysisReport = learningAnalysisService.generateLearningAnalysisReport(userID, belongBook);
            return Result.success(analysisReport);
        } catch (Exception e) {
            return Result.error("500", "分析报告生成失败：" + e.getMessage());
        }
    }

    /**
     * 获取个性化学习建议
     * 
     * @param userID     用户ID
     * @param belongBook 所属词书
     * @return 学习建议
     */
    @PostMapping("/advice/{userID}/{belongBook}")
    public Result<?> getLearningAdvice(@PathVariable String userID, @PathVariable String belongBook) {
        try {
            String advice = learningAnalysisService.generateLearningAdvice(userID, belongBook);
            return Result.success(advice);
        } catch (Exception e) {
            return Result.error("500", "学习建议生成失败：" + e.getMessage());
        }
    }

    /**
     * 获取遗忘风险预警
     * 
     * @param userID 用户ID
     * @return 遗忘风险分析
     */
    @PostMapping("/forgetting-risk/{userID}")
    public Result<?> getForgettingRisk(@PathVariable String userID) {
        try {
            String riskAnalysis = learningAnalysisService.predictForgettingRisk(userID);
            return Result.success(riskAnalysis);
        } catch (Exception e) {
            return Result.error("500", "遗忘风险分析失败：" + e.getMessage());
        }
    }

    /**
     * 获取综合学习洞察（包含统计数据和AI分析）
     * 
     * @param userID     用户ID
     * @param belongBook 所属词书
     * @return 综合学习洞察
     */
    @GetMapping("/insights/{userID}/{belongBook}")
    public Result<?> getLearningInsights(@PathVariable String userID, @PathVariable String belongBook) {
        try {
            // 获取基础统计数据
            List<LineData> lineChartData = statisticService.findLatestSevenDaysTimeData(userID);
            List<ColumnData> columnChartData = statisticService.findLatestSevenDaysWordData(userID);
            List<CircleData> circleChartData = statisticService.findMmryPercentage(userID);
            int learnedWordCount = statisticService.getLearnedWordCount(userID);
            int totalWordCount = statisticService.getTotalWordCount(belongBook);
            int needReviewWordCount = statisticService.getNeedReviewWordCount(userID);

            StatisticData statisticData = new StatisticData(needReviewWordCount, learnedWordCount, totalWordCount,
                    columnChartData, circleChartData, lineChartData);

            // 异步获取AI分析（避免阻塞)
            String quickAnalysis = learningAnalysisService.generateLearningAnalysisReport(userID, belongBook);

            // 构建综合洞察响应
            LearningInsightData insightData = new LearningInsightData(statisticData, quickAnalysis);

            return Result.success(insightData);
        } catch (Exception e) {
            return Result.error("500", "学习洞察获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取背诵效率分析建议（纯建议，不影响现有功能）
     * 
     * @param userID     用户ID
     * @param belongBook 所属词书
     * @return 背诵效率分析和建议
     */
    @PostMapping("/memorization-efficiency/{userID}/{belongBook}")
    public Result<?> getMemorizationEfficiencyAnalysis(@PathVariable String userID, @PathVariable String belongBook) {
        try {
            String efficiencyAnalysis = learningAnalysisService.analyzeMemorizationEfficiency(userID, belongBook);
            return Result.success(efficiencyAnalysis);
        } catch (Exception e) {
            return Result.error("500", "背诵效率分析失败：" + e.getMessage());
        }
    }

    /**
     * 获取背诵模式识别和建议（纯建议，不影响现有功能）
     * 
     * @param userID 用户ID
     * @return 背诵模式分析
     */
    @PostMapping("/memorization-pattern/{userID}")
    public Result<?> getMemorizationPattern(@PathVariable String userID) {
        try {
            String patternAnalysis = learningAnalysisService.analyzeMemorizationPattern(userID);
            return Result.success(patternAnalysis);
        } catch (Exception e) {
            return Result.error("500", "背诵模式分析失败：" + e.getMessage());
        }
    }

    /**
     * 获取词汇记忆强度分析（纯建议，不影响现有功能）
     * 
     * @param userID     用户ID
     * @param belongBook 所属词书
     * @return 词汇记忆强度分析
     */
    @PostMapping("/memory-strength/{userID}/{belongBook}")
    public Result<?> getMemoryStrengthAnalysis(@PathVariable String userID, @PathVariable String belongBook) {
        try {
            String strengthAnalysis = learningAnalysisService.analyzeMemoryStrength(userID, belongBook);
            return Result.success(strengthAnalysis);
        } catch (Exception e) {
            return Result.error("500", "记忆强度分析失败：" + e.getMessage());
        }
    }

    /**
     * 获取学习时间质量分析（纯建议，不影响现有功能）
     * 
     * @param userID 用户ID
     * @return 学习时间质量分析
     */
    @PostMapping("/study-time-quality/{userID}")
    public Result<?> getStudyTimeQualityAnalysis(@PathVariable String userID) {
        try {
            String qualityAnalysis = learningAnalysisService.analyzeStudyTimeQuality(userID);
            return Result.success(qualityAnalysis);
        } catch (Exception e) {
            return Result.error("500", "学习时间质量分析失败：" + e.getMessage());
        }
    }

    /**
     * 获取个性化背诵策略推荐（纯建议，不影响现有功能）
     * 
     * @param userID     用户ID
     * @param belongBook 所属词书
     * @return 个性化背诵策略
     */
    @PostMapping("/memorization-strategy/{userID}/{belongBook}")
    public Result<?> getMemorizationStrategy(@PathVariable String userID, @PathVariable String belongBook) {
        try {
            String strategy = learningAnalysisService.generateMemorizationStrategy(userID, belongBook);
            return Result.success(strategy);
        } catch (Exception e) {
            return Result.error("500", "背诵策略生成失败：" + e.getMessage());
        }
    }

}
